#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <event2/keyvalq_struct.h>

#include "../src/main.h"
#include "../src/xmalloc.h"
#include "../src/log.h"


static struct event_base *base;
static struct evhttp *http;
static struct evhttp_bound_socket *handle;


static void
send_document_cb(struct evhttp_request *req __attribute__((__unused__)), void *arg __attribute__((__unused__)))
{
  return;
}

static int
httpd_run(const char *listen_addr, const uint16_t port) {
  base = event_base_new();

  if (!base) {
    E2("Couldn't create an event_base: exiting");
    return (1);
  }

  /* Create a new evhttp object to handle requests. */
  http = evhttp_new(base);
  if (!http) {
    E2("Couldn't create evhttp: exiting");
    return (2); 
  }

  /* We want to accept arbitrary requests, so we need to set a "generic"
   * cb. We can also add callbacks for specific paths. */
  evhttp_set_gencb(http, send_document_cb, NULL);
  evhttp_set_timeout(http, 10);

  /* Now we tell the evhttp what port to listen on */
  handle = evhttp_bind_socket_with_handle(http, listen_addr, port);
  if (!handle) {
    E("Couldn't bind to port %d", (int)port);
    exit (3);
  }

  if (event_base_loop(base, EVLOOP_NONBLOCK) == -1) {
    E2_errstr("Loop error");
    return (4);
  }

  return (0);
}

static int
httpd_exit(void) {
  int ret = event_base_loopexit(base, NULL);
  if (ret != 0) return (ret);
  printf("event httpd test\n");
  evhttp_free(http);
  event_base_free(base);
  return (ret);
}

int
main(int argc, char **argv) {
  int ret = httpd_run("127.0.0.1", 8000);

  if (ret != 0) return (ret);
  sleep(1);
  if (httpd_exit() != 0) return (5);
  return (0);
}

